package logic.strategy;

import java.util.ArrayList;
import java.util.HashMap;
import logic.Country;
import logic.moves.AddSoldierMove;
import logic.moves.AttackMove;
import logic.moves.GameMove;

public class RandomStrategy extends Strategy {

	private int attacks;
	
	public RandomStrategy()
	{
	}
	public GameMove getNextMove() {
		if(player.getSoldiers() > 0)
		{
			int rIdx = rand.nextInt(player.getCountries().size());
			Country country = player.getCountryByIndex(rIdx);	
			GameMove addMove = new AddSoldierMove(player, country, 1);
			return addMove;
		}
		if(hasPossibleAttack())
		{
			ArrayList<Country> rs = new ArrayList<Country>();
		
			for(Country country: player.getCountries().values())
			{
				if(country.canAttack() && country.getAttackTargets().size() > 0)
					rs.add(country);
			}
			if (rs.isEmpty())
				return null; // should never happen if getnextMove used after hasNextMove
			Country countryAttacking = rs.get(rand.nextInt(rs.size()));
			++attacks;
			rs = countryAttacking.getAttackTargets();
			GameMove attackMove = new AttackMove(countryAttacking, rs.get(rand.nextInt(rs.size())));
			return attackMove;	
		}
		return null;
	}
	/**
	 * 
	 * @return true if player owns a country that may perform attack
	 * and this country has neighbor that may be attacked
	 * 
	 */
	private boolean hasPossibleAttack()
	{
		for(Country country: player.getCountries().values())
		{
			if (country.canAttack() && country.getAttackTargets().size() > 0)
				return true;
		}
		return false;
	}
	/**
	 *	@return true if has free soldiers to place
	 *	or has a possible attack target
	 *	In order random strategy will not exasperate in one turn
	 *	all of its armies, will return false after 5 attacks
	 */
	public boolean hasNextMove()
	{
		if(attacks == 5 && player.getSoldiers() == 0)
		{
			attacks = 0;
			return false;
		}
		return player.getCountries().size() > 0 && 
					(player.getSoldiers() > 0 || hasPossibleAttack());	
	}
	
	public HashMap<String, Country> getTargetCountries() {
		return null;
	}
}
